<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools>
        <!-- 左侧插槽 -->
        <template #left>总记录数：{{ total }} 条</template>

        <!-- 右侧插槽 -->
        <template #right>
          <el-button v-if="checkPermission('excelGo')" type="warning" size="small" @click="$router.push('/import?type=employee')">导入</el-button>
          <el-button type="danger" size="small" @click="handleDownload">导出</el-button>
          <el-button type="primary" size="small" icon="el-icon-plus" @click="showDialog=true">新增员工</el-button>
        </template>
      </page-tools>

      <!-- 放置表格和分页 -->
      <el-card style="margin-top: 10px">
        <el-table border :data="list">
          <el-table-column align="center" label="序号" sortable type="index" :index="indexMethod" width="100" />
          <el-table-column align="center" label="姓名" sortable prop="username" />

          <el-table-column label="头像" align="center">
            <template slot-scope="{row}">
              <img
                v-imgerror="require('@/assets/common/bigUserHeader.png')"
                :src="row.staffPhoto "
                style="border-radius: 50%; width: 100px; height: 100px; padding: 10px"
                alt=""
                @click="showQrCode(row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column align="center" label="手机号" sortable prop="mobile" />
          <el-table-column align="center" label="工号" sortable prop="workNumber" />
          <el-table-column :formatter="formatEmployees" align="center" label="聘用形式" prop="formOfEmployment" />
          <el-table-column align="center" label="部门" sortable prop="departmentName" />
          <el-table-column align="center" label="入职时间" sortable>
            <template v-slot="{row}">
              {{ row.timeOfEntry | formatTime }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="账户状态" sortable>
            <template v-slot="{row}">
              <el-switch
                :value="row.enableState === 1"
                active-color="#13ce66"
                inactive-color="#ff4949"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="280" fixed="right" align="center">
            <template v-slot="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="showAssign(row.id)">角色</el-button>
              <el-button type="text" size="small" @click="deleteEmployee(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="end" align="middle" style="height: 60px">
          <el-pagination
            layout="prev, pager, next"
            :total="total"
            background
            :page-size="size"
            :current-page="page"
            @current-change="change"
          />
        </el-row>
      </el-card>

      <!-- 弹出对话框组件 （添加）-->
      <add-employee :show-dialog.sync="showDialog" />

      <!-- 分配角色对话框组件 -->
      <assign-role :show-role-dialog.sync="showRoleDialog" :role-ids="roleIds" />

      <!-- 二维码对话框 -->
      <el-dialog title="二维码" width="40%" :visible.sync="showCodeDialog">
        <el-row type="flex" justify="center">
          <canvas ref="myCanvas" />
        </el-row>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getEmployeeList, delEmployee } from '@/api/employees'
// 导入 api/constant文件夹下的常量
import employments from '@/api/constant/employees'

import AddEmployee from './components/add-employee'
import { formatTime } from '@/filters'

import QrCode from 'qrcode'

// 分配角色组件
import AssignRole from './components/assign-role'
import permission from '@/Mixins/permission'
export default {
  name: 'Employees',
  components: {
    AddEmployee,
    AssignRole
  },
  mixins: [permission],
  data() {
    return {
      // 员工
      list: [],
      // 总条数
      total: 0,
      page: 1,
      // 一页多少数据
      size: 5,
      // 对话框显示，隐藏(父组件，提供，再传给子组件)
      showDialog: false,
      // 二维码弹窗
      showCodeDialog: false,
      // 分配权限弹窗
      showRoleDialog: false,
      // 存角色的id，传给子组件（发送请求）
      roleIds: ''
    }
  },

  created() {
    // 获取所有员工
    this.getEmployeeList()
  },

  methods: {

    // 个人信息中是否有按钮权限(角色没有匹配到按钮权限标识的)
    // checkPermission(key) {
    //   // key标识
    //   // 获取到vuex中的数据
    //   const points = this.$store.state.user.userInfo.roles.points
    //   return points.includes(key)
    // },
    // 获取所有员工
    async getEmployeeList() {
      const res = await getEmployeeList(this.page, this.size)
      console.log(res)
      this.total = res.total
      this.list = res.rows
    },

    // 修改分页
    change(value) {
      this.page = value
      this.getEmployeeList()
    },

    // 修正序号
    indexMethod(index) {
      // 就是计算点击的前一页有多少数据
      return index + 1 + (this.page - 1) * this.size
    },

    // 格式化聘用形式
    formatEmployees(row, column, cellValue, index) {
      // cellValue显示的值
      const result = employments.hireType.find(item => item.id === cellValue)
      return result ? result.value : ''
    },

    // 删除员工
    async  deleteEmployee(id) {
      try {
        await this.$confirm('您确定删除该员工吗', '温馨提示', {
          type: 'warning'
        })
      } catch (error) {
        return
      }
      if (this.list.length === 1 && this.page > 1) {
        this.page--
      }
      await delEmployee(id)
      this.$message.success('删除员工成功')
      this.getEmployeeList()
    },

    // 数据更新后，跳转到最后一页
    goEndPage() {
      this.total++
      this.page = Math.ceil(this.total / this.size)
    },

    // 导出
    handleDownload() {
      import('@/vendor/Export2Excel').then(async excel => {
        // 发送请求获取所有员工数据
        const res = await getEmployeeList(1, this.total)
        // console.log(res.rows)

        // 表头
        const headers = {
          '手机号': 'mobile',
          '姓名': 'username',
          '入职日期': 'timeOfEntry',
          '聘用形式': 'formOfEmployment',
          '转正日期': 'correctionTime',
          '工号': 'workNumber',
          '部门': 'departmentName'
        }
        // 复杂表头
        const multiHeader = [['姓名', '主要信息', '', '', '', '', '部门']]
        // 合并复杂表头格式
        const merges = ['A1:A2', 'B1:F1', 'G1:G2']

        const tHeader = Object.keys(headers)
        // console.log(theader) // ["手机号", "姓名", "入职日期", "聘用形式", "转正日期", "工号", "部门"]
        // 数据
        const data = res.rows.map(item => {
          // console.log(item)
          return tHeader.map(v => {
            // 如果数据为空，就返回空
            if (!item[headers[v]]) return item[headers[v]]
            // 格式化时间
            if (v === '入职日期' || v === '转正日期') {
              return formatTime(item[headers[v]])
            }
            // 聘用形式
            if (v === '聘用形式') {
              return employments.hireType.find(i => i.id === item[headers[v]]).value
            }
            // console.log(v)
            // console.log(headers[v])
            return item[headers[v]]
          })
        })
        console.log(data)
        /* 举例 格式 */
        // const tHeader = ['姓名', '年龄', '工资']
        // const data = [
        //   ['张三', 18, 2000],
        //   ['李四', 20, 3000]
        // ]

        // excel生成
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: '员工',
          autoWidth: true,
          bookType: 'xlsx',

          multiHeader, // 复杂表头
          merges // 合并选项
        })
      })
    },

    // 在点击员工的图片时，显示弹层，并将图片地址转化成二维码
    async showQrCode(url) {
      if (!url) return
      this.showCodeDialog = true
      // 将图片地址生成二维码

      await this.$nextTick()
      // 参数1： 获取canvas标签，
      // 参数2： url地址
      QrCode.toCanvas(this.$refs.myCanvas, url)
    },

    // 分配权限对话框
    showAssign(id) {
      this.showRoleDialog = true
      // 存id
      this.roleIds = id
    }
  }
}
</script>

<style>

</style>
